package com.hlkj.warboot.configurer.redis;

import org.springframework.boot.autoconfigure.AutoConfigureAfter;
import org.springframework.boot.autoconfigure.data.redis.RedisAutoConfiguration;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.PlatformTransactionManager;

import javax.sql.DataSource;

/**
 * @Description TODO 自定义RedisTemplate模板
 * 1、StringRedisTemplate模板继承于RedisTemplate，采用的是String的序列化策略，把key和value序列化成字符串保存
 * @Author 李星
 * @Date 2019/6/29 22:50
 */
@Configuration
@AutoConfigureAfter(RedisAutoConfiguration.class)
public class RedisConfig {

    /**
     * 自定定义redis模板对象
     */
    @Bean
    public RedisTemplate<String, Object> redisTemplate(LettuceConnectionFactory redisConnectionFactory) {
        // TODO 创建模板对象
        RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>();

        // TODO 开启redis事务（仅支持单机，不支持cluster）
        redisTemplate.setEnableTransactionSupport(true);

        // TODO 配置基于 lettuce 的连接工厂
        redisTemplate.setConnectionFactory(redisConnectionFactory);

        // TODO 使用 StringRedisSerializer 序列化、反序列化 key
        StringRedisSerializer stringRedisSerializer = new StringRedisSerializer();
        redisTemplate.setKeySerializer(stringRedisSerializer);
        redisTemplate.setHashKeySerializer(stringRedisSerializer);

        // TODO 使用 Jackson2JsonRedisSerializer 序列化、反序列化 value，默认采用的是JDK的序列化器
        Jackson2JsonRedisSerializer<Object> jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer<>(Object.class);
        redisTemplate.setValueSerializer(jackson2JsonRedisSerializer);
        redisTemplate.setHashValueSerializer(jackson2JsonRedisSerializer);

        // TODO 配置默认序列化与反序列化工具类
        redisTemplate.afterPropertiesSet();
        return redisTemplate;
    }

    /**
     * SpringBoot整合Redis事务：配置事务管理器
     *
     * redis事务依赖于jdbc的事务管理，所以还需要引入jdbc
     * <dependency>
     *      <groupId>org.springframework.boot</groupId>
     *      <artifactId>spring-boot-starter-jdbc</artifactId>
     * </dependency>
     */
    @Bean
    public PlatformTransactionManager transactionManager(DataSource dataSource){
        return new DataSourceTransactionManager(dataSource);
    }

}
